package com.zy.activity.adapter

import com.zy.utils.ActivityUtils.showViewTree
import com.zy.activity.bean.BaseMenuBean
import androidx.recyclerview.widget.RecyclerView
import com.zy.activity.adapter.BaseActivityAdapter.BaseViewHolder
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import com.zy.activity.R
import android.widget.TextView

class BaseActivityAdapter(var mainBeanList: List<BaseMenuBean>) : RecyclerView.Adapter<BaseViewHolder>() {
    private var clickCallBack: ClickCallBack? = null
    fun setClickCallBack(clickCallBack: ClickCallBack?) {
        this.clickCallBack = clickCallBack
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, type: Int): BaseViewHolder {
        return if (type == BaseMenuBean.HEAD) {
            val view = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.base_menu_head_item, viewGroup, false)
            BaseHeadViewHolder(view)
        } else {
            val view = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.base_menu_body_item, viewGroup, false)
            BaseBodyViewHolder(view)
        }
    }

    override fun onBindViewHolder(viewHolder: BaseViewHolder, position: Int) {
        viewHolder.bind(mainBeanList[position])
    }

    override fun getItemViewType(position: Int): Int {
        return mainBeanList[position].type
    }

    override fun getItemCount(): Int {
        return mainBeanList.size
    }

    abstract inner class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        abstract fun bind(bean: BaseMenuBean?)
    }

    internal inner class BaseHeadViewHolder(itemView: View) : BaseViewHolder(itemView) {
        private val title: TextView

        init {
            title = itemView.findViewById(R.id.base_menu_head_title)
        }

        override fun bind(bean: BaseMenuBean?) {
            if (bean != null) {
                title.text = bean.des
            }
        }
    }

    internal inner class BaseBodyViewHolder(itemView: View) : BaseViewHolder(itemView) {
        private val title: Button
        private var bean: BaseMenuBean? = null

        init {
            title = itemView.findViewById(R.id.base_menu_item_title)
            title.setOnClickListener { v ->
                showViewTree(v)
                clickCallBack?.let {
                    bean?.let { b ->
                        it.click(b)
                    }
                }
            }
        }

        override fun bind(bean: BaseMenuBean?) {
            this.bean = bean
            if (this.bean != null) {
                title.text = this.bean!!.des
            }
        }
    }

    interface ClickCallBack {
        fun click(bean: BaseMenuBean)
    }
}